import axios from 'axios';
import {ElMessage} from 'element-plus';

const service = axios.create({
  baseURL: '/api',
  timeout: 5000
});

service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code !== 200) {
      if (response.config.alert) {
        ElMessage({
          message: res.msg || "服务器错误，请稍后再试",
          type: 'error',
          duration: 2000
        });
      }
      return Promise.reject(new Error(res.message || 'Error'));
    } else {
      return res;
    }
  },
  error => {
    console.log('err' + error);
    ElMessage({
      message: '服务器错误，请稍后再试',
      type: 'error',
      duration: 2000
    });
    return Promise.reject(error);
  }
);

export default service;